﻿using System;
using System.Drawing.Imaging;
using System.IO;

using SsrsRenderStudio.Shared;

namespace SsrsRenderStudio.Renderer.Support
{
    public class MetafileBuilderInstance
    {
        /// <summary>
        /// Convert rendered stream into an array of metafiles.
        /// </summary>
        public Metafile[] BuildMetafiles(byte[][] renderedReport)
        {
            if (renderedReport.Length > 0)
            {
                Metafile[] metas = new Metafile[renderedReport.Length];

                for (int i = 0; i < renderedReport.Length; i++)
                {
                    metas[i] = getMetafileFromBuffer(renderedReport[i]);

                    Logger.Log("80000", renderedReport[i].Length.ToString());
                    Logger.Log("80001",i.ToString() , metas[i].Width.ToString() , metas[i].HorizontalResolution.ToString() , metas[i].Height.ToString() , metas[i].VerticalResolution.ToString() , metas[i].PhysicalDimension.Width.ToString() , metas[i].PhysicalDimension.Height.ToString());
                }

                return metas;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Create a metafile from stream
        /// </summary>
        private Metafile getMetafileFromBuffer(byte[] buffer)
        {
            try
            {
                MemoryStream ms = new MemoryStream(buffer);
                ms.Position = 0;
                return new Metafile((Stream)ms);
            }
            catch
            {
                return null;
            }
        }
    }
}
